import React, { Component, PropTypes } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { propType, filter } from 'graphql-anywhere';
import { View, ScrollView, StyleSheet, ActivityIndicator } from 'react-native';
import { Grid, Row, Col, Icon } from 'react-native-elements';
import ClothGridItem from './ClothGridItem';
import EmptyView from '../widgets/EmptyView';

const styles = StyleSheet.create({
  left: {
    flexDirection: 'row',
    justifyContent: 'flex-start'
  },
  right: {
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  spinner: {
    marginTop: 100
  },
  empty: {
    height: 200
  }
});

const ClothGrid = ({loading, clothes, onSelect}) => {
  if (loading||!clothes) {
    return <ActivityIndicator style={styles.spinner}/>;
  } else if (clothes.length>0) {
    return (
      <Grid>
        {
          Array.apply(null, Array(Math.ceil(clothes.length/2)))
            .map((i, index) => {
              const leftCloth = clothes[index*2];
              const rightCloth = clothes[index*2+1];

              return (
                <Row key={index}>
                  <Col>
                    <View style={styles.left}>
                      {leftCloth&&<ClothGridItem onSelect={onSelect} cloth={filter(ClothGridItem.fragments.cloth, leftCloth)}/>}
                    </View>
                  </Col>
                  <Col>
                    <View style={styles.right}>
                      {rightCloth&&<ClothGridItem onSelect={onSelect} cloth={filter(ClothGridItem.fragments.cloth, rightCloth)}/>}
                    </View>
                  </Col>
                </Row>
              );
            })
        }
      </Grid>
    );
  } else {
    return <View style={styles.empty}><EmptyView/></View>;
  }
}

ClothGrid.propTypes = {
  chinese: PropTypes.bool,
  onSelect: PropTypes.func
};

const configs = {
  options: ({search, categoryId, type}) => {
    return {
      variables: {
        search,
        type,
        ...categoryId&&{
          categoryIds: [categoryId]
        }
      }
    };
  },
  props: ({ownProps, data:{clothes, refetch, loading}}) => {
    return {
      clothes,
      refetch,
      loading
    };
  }
};

export const LaundryGrid = graphql(gql`
  query LaudnryClothGrid($search:String,$categoryIds:[String]) {
    clothes(search:$search,type:"laundry",categoryIds:$categoryIds) {
      ...ClothGridItem
    }
  }
  ${ClothGridItem.fragments.cloth}
`, configs)(ClothGrid);

export const PremiumLaundryGrid = graphql(gql`
  query PremiumLaundryClothGrid($search:String) {
    clothes(search:$search,type:"premiumlaundry") {
      ...ClothGridItem
    }
  }
  ${ClothGridItem.fragments.cloth}
`, configs)(ClothGrid);
